package com.example.springsecurity.security;

import com.alibaba.fastjson.JSONObject;
import com.example.springsecurity.common.CommonResult;
import com.example.springsecurity.security.dto.LoginUserDto;
import com.example.springsecurity.serivce.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author wuancheng
 * @date 2024/6/19 18:40
 * @description 推出处理
 */
@Configuration
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private TokenService tokenService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String token = request.getHeader("token");
        if (StringUtils.isNotBlank(token)) {
            LoginUserDto loginUserDto = tokenService.verifyToken(token);
            redisTemplate.delete(TokenService.USER_KEY + loginUserDto.getId());
        }
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.getWriter().println(JSONObject.toJSONString(CommonResult.succeed()));
    }
}
